package com.weightx.weight.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weightx.weight.common.JwtUtil;
import com.weightx.weight.common.R;
import com.weightx.weight.constant.MyConstant;
import com.weightx.weight.entity.*;
import com.weightx.weight.mapper.*;
import com.weightx.weight.properties.UploadProperties;
import com.weightx.weight.service.*;
import com.weightx.weight.utils.ExcelUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Stream;

@RequestMapping
@RestController
public class DataController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IDataService dataService;

    @Autowired
    private IAdviceService adviceService;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private IFileService fileService;

    @Autowired
    private ITheoryService theoryService;

    @Autowired
    private TheoryMapper theoryMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private INewsService inewsService;

    @Autowired
    private NewsMapper newsMapper;

    @Autowired
    private HomeAdsMapper homeAdsMapper;

    @Autowired
    private IHomeAdsService homeAdsService;

    @Autowired
    private FloorAdsMapper floorAdsMapper;

    @Autowired
    private IFloorAdsService floorAdsService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UploadProperties uploadProperties;

    public DataController(UploadProperties uploadProperties) {
        this.uploadProperties = uploadProperties;
    }

    private final String[] acceptSuffixs = new String[]{".xlsx", ".txt"};


    @RequestMapping("/add")
    public R addData(@RequestBody AddRequest addRequest) throws ParseException {
        String openid = addRequest.getOpenid();
        Float weight = addRequest.getWeight();
        String date = addRequest.getDate();
        Integer type = addRequest.getType();
        if (openid == null || openid.isEmpty() || weight == null) {
            return R.error();
        }
        user u = userService.getBaseMapper().selectOne(new QueryWrapper<user>().eq("openid", openid));
        if (u != null) {
            Long uid = u.getUserid();
            // 用户存在
            data d = new data();
            d.setUserid(uid);
            d.setWeight(weight);
            d.setDate(date == null ? new Date() : DateUtils.parseDate(date, "yyyy-MM-dd HH:mm:ss"));
            d.setType(type == null ? 0 : type);
            dataService.getBaseMapper().insert(d);
            return R.success();
        } else {
            // 用户不存在
            return R.error();
        }

    }

    @RequestMapping("/delete")
    public R delete(@RequestBody DeleteRequest request) {
        String openid = request.getOpenid();
        // 将按日期删除记录更改为按记录id主键删除
        // Date date = request.getDate();
        String dataid = request.getDataid();
        if (openid == null || openid.isEmpty() || dataid == null) {
            return R.error();
        }
        user u = userService.getBaseMapper().selectOne(new QueryWrapper<user>().eq("openid", openid));
        if (u != null) {
            int result = dataService.getBaseMapper().delete(new QueryWrapper<data>().lambda().eq(data::getUserid, u.getUserid()).eq(data::getDataid, dataid));
            if (result > 0) {
                return R.success();
            } else {
                return R.error(1003, "删除失败，没有找到记录");
            }
        }
        return R.error();

    }

    @GetMapping("/downloadUser")
    public void downloadUser(HttpServletResponse response) {
        try {
            //if (!checkToken(token)) {
            //    response.setContentType("application/json");
            //    response.setCharacterEncoding("UTF-8");
            //
            //    ObjectMapper mapper = new ObjectMapper();
            //    mapper.writeValue(response.getWriter(), R.error());
            //    return;
            //}

            XSSFWorkbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Data");
            int rowNum = 0;
            Row headerRow = sheet.createRow(rowNum++);
            headerRow.createCell(0).setCellValue("UnionID");
            headerRow.createCell(1).setCellValue("首次登录日期");
            headerRow.createCell(2).setCellValue("最近一次登录日期");
            headerRow.createCell(3).setCellValue("最近30天记录天数");
            headerRow.createCell(4).setCellValue("总记录的天数");
            headerRow.createCell(5).setCellValue("目标体重");
            headerRow.createCell(6).setCellValue("设置单位");
            headerRow.createCell(7).setCellValue("身高");
            headerRow.createCell(8).setCellValue("性别");
            headerRow.createCell(9).setCellValue("出身年份");
            headerRow.createCell(10).setCellValue("进入过提醒我");

            List<user> userList = userService.getBaseMapper().selectList(null);
            for (user it : userList) {
                // 获取当前时间
                long endtime = System.currentTimeMillis();
                // 获取30天前的时间
                long begintime = endtime - (1000L * 60 * 60 * 24 * 30);
                Date beginTime = new Date(begintime);
                Date endTime = new Date(endtime);
                QueryWrapper<data> wrapper = new QueryWrapper<data>()
                        .eq("userid", it.getUserid())
                        .isNotNull("date");
                QueryWrapper<data> addNumAll = wrapper.select("COUNT(DISTINCT DATE_FORMAT(date, '%Y-%m-%d')) AS count")
                        .groupBy("DATE_FORMAT(date, '%Y-%m-%d')");
                List<Map<String,Object>> addNumAllList = dataService.getBaseMapper().selectMaps(addNumAll);
                List<data> thirtyDaysAgo = dataService.getBaseMapper().selectList(wrapper
                        .ge("date", beginTime)
                        .le("date", endTime));
                System.out.println("addNumAllList" + addNumAllList);
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(it.getOpenid());
                row.createCell(1).setCellValue(com.weightx.weight.utils.DateUtils.formatDate(it.getRegisterTime()));
                row.createCell(2).setCellValue(com.weightx.weight.utils.DateUtils.formatDate(it.getLoginTime()));
                row.createCell(3).setCellValue(thirtyDaysAgo.size());
                row.createCell(4).setCellValue(addNumAllList.size());
                row.createCell(5).setCellValue(it.getTargetWeight() == null ? "null" : it.getTargetWeight().toString());
                row.createCell(6).setCellValue(it.getUnit() == 0 ? "千克" : "斤");
                row.createCell(7).setCellValue(it.getBodyHeight() == null ? "null" : it.getBodyHeight().toString());
                row.createCell(8).setCellValue(it.getSex() == null ? "null" : (it.getSex() == 0 ? "男" : "女"));
                row.createCell(9).setCellValue(it.getBirth() == null ? "null" : com.weightx.weight.utils.DateUtils.formatYear(it.getBirth()));
                row.createCell(10).setCellValue(it.getRemind() == 0 ? "否" : "是");
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=user_info_" + new Date().getTime() + ".xlsx");
            // 将 Excel 文件写入响应体
            try (OutputStream out = response.getOutputStream()) {
                workbook.write(out);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/downloadAdvice")
    public void downloadAdvice(HttpServletResponse response) {
        try {
            //if (!checkToken(token)) {
            //    response.setContentType("application/json");
            //    response.setCharacterEncoding("UTF-8");
            //
            //    ObjectMapper mapper = new ObjectMapper();
            //    mapper.writeValue(response.getWriter(), R.error());
            //    return;
            //}

            XSSFWorkbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Data");
            int rowNum = 0;
            Row headerRow = sheet.createRow(rowNum++);
            headerRow.createCell(0).setCellValue("提交日期");
            headerRow.createCell(1).setCellValue("UnionID");
            headerRow.createCell(2).setCellValue("建议");

            List<advice> adviceList = adviceService.getBaseMapper().selectList(new QueryWrapper<advice>().lambda().orderByDesc(advice::getDate));
            for (advice it : adviceList) {
                user u = userService.getBaseMapper().selectById(it.getUserid());
                if (u == null) {
                    continue;
                }
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(com.weightx.weight.utils.DateUtils.formatDate(it.getDate()));
                row.createCell(1).setCellValue(u.getOpenid());
                row.createCell(2).setCellValue(it.getContent());
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=advice_info_" + new Date().getTime() + ".xlsx");
            // 将 Excel 文件写入响应体
            try (OutputStream out = response.getOutputStream()) {
                workbook.write(out);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/downloadWeight")
    public void downloadWeight(HttpServletResponse response) {
        try {
            //if (!checkToken(token)) {
            //    response.setContentType("application/json");
            //    response.setCharacterEncoding("UTF-8");
            //
            //    ObjectMapper mapper = new ObjectMapper();
            //    mapper.writeValue(response.getWriter(), R.error());
            //    return;
            //}

            XSSFWorkbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Data");

            int rowNum = 0;
            Row headerRow = sheet.createRow(rowNum++);
            headerRow.createCell(0);
            headerRow.createCell(1).setCellValue("新登录人数");
            headerRow.createCell(2).setCellValue("记录体重人数");
            headerRow.createCell(3).setCellValue("记录体重条数");
            headerRow.createCell(4);
            headerRow.createCell(5).setCellValue("随记条数");
            headerRow.createCell(6).setCellValue("起床空腹条数");
            headerRow.createCell(7).setCellValue("睡前条数");
            headerRow.createCell(8).setCellValue("正餐前条数");
            headerRow.createCell(9).setCellValue("正餐后条数");
            headerRow.createCell(10);
            headerRow.createCell(11).setCellValue("设置目标人数");
            headerRow.createCell(12).setCellValue("累计用户人数");
            headerRow.createCell(13).setCellValue("小于等于7天内有记录体重的人数");
            headerRow.createCell(14).setCellValue("大于7天，小于等于15天有记录体重的人数");
            headerRow.createCell(15).setCellValue("大于15天，小于等于30天有记录体重的人数");
            headerRow.createCell(16).setCellValue("大于30天，小于等于90天有体重记录的人数");
            //
            //// 定义查询的日期范围
            //long endTime = System.currentTimeMillis();
            //long beginTime = endTime-1000L*60*60*24*90;
            //for(long tempTime = beginTime; tempTime<=endTime;){
            //    long tempEndTime = (tempTime+1000L*60*60*24);
            //    // 构造查询条件
            //    Date queryStart = new Date(tempTime);
            //    Date queryEnd = new Date(tempEndTime);
            //    // 构造条件
            //    // 七天内
            //    long tempTimeSeven = tempTime-1000L*60*60*24*7;
            //    Date tempSeven = new Date(tempTimeSeven);
            //    // 大于7天，小于15天
            //    long tempTimeFifteen = tempTime-1000L*60*60*24*15;
            //    Date tempFifteen = new Date(tempTimeFifteen);
            //    // 大于15天，小于30天
            //    long tempTimeThirty = tempTime-1000L*60*60*24*30;
            //    Date tempThirty = new Date(tempTimeThirty);
            //    // 大于30天，小于90天
            //    long tempTimeNinety = tempTime-1000L*60*60*24*90;
            //    Date tempNinety = new Date(tempTimeNinety);
            //    List<user> userList = userService.getBaseMapper().selectList(new QueryWrapper<user>().lambda().between(user::getLoginTime, queryStart, queryEnd));
            //    List<data> dataList = dataService.getBaseMapper().selectList(new QueryWrapper<data>().lambda().between(data::getDate, queryStart, queryEnd));
            //
            //    Integer num0 = userService.getBaseMapper().selectList(new QueryWrapper<user>().lambda().between(user::getRegisterTime, queryStart, queryEnd)).size();
            //    Long num1 = dataList.stream().map(data::getUserid).distinct().count();
            //    Integer num2 = dataList.size();
            //
            //    Long num4 = dataList.stream().filter(it -> Objects.equals(it.getType(), MyConstant.WEIGHT_TYPE_DEFAULT)).count();
            //    Long num5 = dataList.stream().filter(it -> Objects.equals(it.getType(), MyConstant.WEIGHT_TYPE_EMPTY_STOM)).count();
            //    Long num6 = dataList.stream().filter(it -> Objects.equals(it.getType(), MyConstant.WEIGHT_TYPE_BEFORE_SLEEP)).count();
            //    Long num7 = dataList.stream().filter(it -> Objects.equals(it.getType(), MyConstant.WEIGHT_TYPE_BEFORE_EAT)).count();
            //    Long num8 = dataList.stream().filter(it -> Objects.equals(it.getType(), MyConstant.WEIGHT_TYPE_AFTER_EAT)).count();
            //
            //    Long num10 = userList.stream().filter(it -> it.getTargetWeight() != null).count();
            //    Long num11 = userService.getBaseMapper().selectCount(new QueryWrapper<user>().lambda().lt(user::getRegisterTime, queryEnd));
            //    Long num12 = dataService.getBaseMapper().selectList(new QueryWrapper<data>().lambda().between(data::getDate, tempSeven,queryStart)).stream().map(data::getUserid).distinct().count();
            //    Long num13 = dataService.getBaseMapper().selectList(new QueryWrapper<data>().lambda().between(data::getDate,tempFifteen,tempSeven)).stream().map(data::getUserid).distinct().count();
            //    Long num14 = dataService.getBaseMapper().selectList(new QueryWrapper<data>().lambda().between(data::getDate, tempThirty,tempFifteen)).stream().map(data::getUserid).distinct().count();
            //    Long num15 = dataService.getBaseMapper().selectList(new QueryWrapper<data>().lambda().between(data::getDate, tempNinety,tempThirty)).stream().map(data::getUserid).distinct().count();
            //
            //
            //    Row row = sheet.createRow(rowNum++);
            //    row.createCell(0).setCellValue(com.weightx.weight.utils.DateUtils.formatDate(queryStart));
            //    row.createCell(1).setCellValue(num0);
            //    row.createCell(2).setCellValue(num1);
            //    row.createCell(3).setCellValue(num2);
            //    row.createCell(4);
            //    row.createCell(5).setCellValue(num4);
            //    row.createCell(6).setCellValue(num5);
            //    row.createCell(7).setCellValue(num6);
            //    row.createCell(8).setCellValue(num7);
            //    row.createCell(9).setCellValue(num8);
            //    row.createCell(10);
            //    row.createCell(11).setCellValue(num10);
            //    row.createCell(12).setCellValue(num11);
            //    row.createCell(13).setCellValue(num12);
            //    row.createCell(14).setCellValue(num13);
            //    row.createCell(15).setCellValue(num14);
            //    row.createCell(16).setCellValue(num15);
            //    tempTime = tempEndTime;
            //}

            // 定义查询的日期范围
            Date startDate = com.weightx.weight.utils.DateUtils.getDateBefore(new Date(), 90);
            Date endDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            while (calendar.getTime().before(endDate) || calendar.getTime().equals(endDate)) {
                // 构造查询条件
                Date queryDate = calendar.getTime();
                Date queryDateStart = DateUtils.truncate(queryDate, Calendar.DAY_OF_MONTH);
                Date queryDateEnd = DateUtils.addDays(queryDateStart, 1);
                List<user> userList = userService.getBaseMapper().selectList(new QueryWrapper<user>().lambda().between(user::getLoginTime, queryDateStart, queryDateEnd));
                List<data> dataList = dataService.getBaseMapper().selectList(new QueryWrapper<data>().lambda().between(data::getDate, queryDateStart, queryDateEnd));
                // 7天内查询条件
                LambdaQueryWrapper<data> sevenWrapper = new QueryWrapper<data>()
                        .lambda()
                        .between(data::getDate,
                                com.weightx.weight.utils.DateUtils.getDateBefore(queryDateStart,7),
                                DateUtils.addDays(queryDate,1));
                // 7至15天查询条件
                LambdaQueryWrapper<data> sevenAndFifteenWrapper = new QueryWrapper<data>()
                        .lambda()
                        .between(data::getDate,
                                com.weightx.weight.utils.DateUtils.getDateBefore(queryDateStart,15),
                                com.weightx.weight.utils.DateUtils.getDateBefore(queryDateStart,8));
                // 15至30天查询条件
                LambdaQueryWrapper<data> thirtyAndFifteenWrapper = new QueryWrapper<data>()
                        .lambda()
                        .between(data::getDate,
                                com.weightx.weight.utils.DateUtils.getDateBefore(queryDateStart,30),
                                com.weightx.weight.utils.DateUtils.getDateBefore(queryDateStart,16));
                // 30至90天查询条件
                LambdaQueryWrapper<data> ninetyAndThirtyWrapper = new QueryWrapper<data>()
                        .lambda()
                        .between(data::getDate,
                                com.weightx.weight.utils.DateUtils.getDateBefore(queryDateStart,90),
                                com.weightx.weight.utils.DateUtils.getDateBefore(queryDateStart,31));

                Integer num0 = userService.getBaseMapper().selectList(new QueryWrapper<user>().lambda().between(user::getRegisterTime, queryDateStart, queryDateEnd)).size();
                Long num1 = dataList.stream().map(data::getUserid).distinct().count();
                Integer num2 = dataList.size();

                Long num4 = dataList.stream().filter(it -> Objects.equals(it.getType(), MyConstant.WEIGHT_TYPE_DEFAULT)).count();
                Long num5 = dataList.stream().filter(it -> Objects.equals(it.getType(), MyConstant.WEIGHT_TYPE_EMPTY_STOM)).count();
                Long num6 = dataList.stream().filter(it -> Objects.equals(it.getType(), MyConstant.WEIGHT_TYPE_BEFORE_SLEEP)).count();
                Long num7 = dataList.stream().filter(it -> Objects.equals(it.getType(), MyConstant.WEIGHT_TYPE_BEFORE_EAT)).count();
                Long num8 = dataList.stream().filter(it -> Objects.equals(it.getType(), MyConstant.WEIGHT_TYPE_AFTER_EAT)).count();

                Long num10 = userList.stream().filter(it -> it.getTargetWeight() != null).count();
                Long num11 = userService.getBaseMapper().selectCount(new QueryWrapper<user>().lambda().lt(user::getRegisterTime, queryDateEnd));
                Long num12 = dataService.getBaseMapper().selectList(sevenWrapper).stream().count();
                System.out.println("7sql"+sevenWrapper.getCustomSqlSegment());
                System.out.println("7"+com.weightx.weight.utils.DateUtils.formatDate(queryDate)+" number"+num12);
                //Long num13 = dataService.getBaseMapper().selectList(new QueryWrapper<data>().lambda().between(data::getDate, com.weightx.weight.utils.DateUtils.getDateBefore(queryDate, 15), com.weightx.weight.utils.DateUtils.getDateBefore(queryDate, 7))).stream().map(data::getUserid).distinct().count();
                Long num13 = dataService.getBaseMapper().selectList(sevenAndFifteenWrapper).stream().map(data::getUserid).distinct().count();
                //Long num14 = dataService.getBaseMapper().selectList(new QueryWrapper<data>().lambda().between(data::getDate, com.weightx.weight.utils.DateUtils.getDateBefore(queryDate, 30), com.weightx.weight.utils.DateUtils.getDateBefore(queryDate, 15))).stream().map(data::getUserid).distinct().count();
                Long num14 = dataService.getBaseMapper().selectList(thirtyAndFifteenWrapper).stream().map(data::getUserid).distinct().count();
                //Long num15 = dataService.getBaseMapper().selectList(new QueryWrapper<data>().lambda().between(data::getDate, com.weightx.weight.utils.DateUtils.getDateBefore(queryDate, 90), com.weightx.weight.utils.DateUtils.getDateBefore(queryDate, 30))).stream().map(data::getUserid).distinct().count();
                Long num15 = dataService.getBaseMapper().selectList(ninetyAndThirtyWrapper).stream().map(data::getUserid).distinct().count();

                // 将日期加1天
                calendar.add(Calendar.DAY_OF_MONTH, 1);

                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(com.weightx.weight.utils.DateUtils.formatDate(queryDate));
                row.createCell(1).setCellValue(num0);
                row.createCell(2).setCellValue(num1);
                row.createCell(3).setCellValue(num2);
                row.createCell(4);
                row.createCell(5).setCellValue(num4);
                row.createCell(6).setCellValue(num5);
                row.createCell(7).setCellValue(num6);
                row.createCell(8).setCellValue(num7);
                row.createCell(9).setCellValue(num8);
                row.createCell(10);
                row.createCell(11).setCellValue(num10);
                row.createCell(12).setCellValue(num11);
                row.createCell(13).setCellValue(num12);
                row.createCell(14).setCellValue(num13);
                row.createCell(15).setCellValue(num14);
                row.createCell(16).setCellValue(num15);

            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=weight_info_" + new Date().getTime() + ".xlsx");
            // 将 Excel 文件写入响应体
            try (OutputStream out = response.getOutputStream()) {
                workbook.write(out);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean checkToken(String token) {
        try {
            Claims claims = jwtUtil.parseToken(token);
            if (jwtUtil.judgeTokenExpiration(claims.getExpiration())) {
                return false;
            }
            Integer uid = Integer.valueOf(claims.getSubject());
            admin a = adminMapper.selectById(uid);
            if (a != null) {
                return true;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return false;
    }

    public Boolean importXlsxUploadTheory(String filePath) throws IOException {
        // 获取文件IO流
        InputStream inputStream = new FileInputStream(filePath);
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        for (int i = 0; i <= sheet.getLastRowNum(); i++) {
            XSSFRow row = sheet.getRow(i);
            if (row != null) {
                theory th = new theory();
                th.setTheory(row.getCell(0).getStringCellValue());
                theoryService.getBaseMapper().insert(th);
            }
        }
        return true;
    }

    public Boolean importTxtTheory(String filePath) throws IOException {
        File file = new File(filePath);
        // 获取文件IO流
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
        String line = null;
        while ((line = br.readLine()) != null) {
            theory th = new theory();
            th.setTheory(line);
            theoryService.getBaseMapper().insert(th);
        }
        return true;
    }

    @PostMapping("/uploadTheory")
    public R uploadTheory(@RequestParam("file") MultipartFile file) throws Exception {
        if (file == null) return R.error("请选择需要上传文件!");
        // 获取上传文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀名
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        // 判断后缀名是否合法
        Boolean flag = Arrays.asList(acceptSuffixs).contains(fileSuffix);
        if (!flag) return R.error("文件格式只能为xlsx或者txt");
        // 获取文件相对路径
        String revealFilePath = "/" + fileName;
        // 存入数据库
        String filePath = uploadProperties.getUploadDir() + revealFilePath;
        // 判断文件是否存在
        File theoryFile = new File(filePath);
        if (theoryFile.exists()) {
            theoryFile.delete();
        }
        file.transferTo(theoryFile);
        // 存入数据库
        file fileInfo = new file();
        fileInfo.setFilename(fileName);
        fileInfo.setFilepath(revealFilePath);
        Long filepath = fileService.getBaseMapper().selectCount(new QueryWrapper<file>().eq("filename", fileName));
        if (filepath != 0) {
            fileMapper.deleteExistFile(fileName);
        }
        int insert = fileService.getBaseMapper().insert(fileInfo);
        if (insert <= 0) return R.error();
        // 清空之前表数据
        theoryMapper.truncateTheory();
        if (fileSuffix.equals(".xlsx")) {
            importXlsxUploadTheory(filePath);
        }
        if (fileSuffix.equals(".txt")) {
            importTxtTheory(filePath);
        }
        return R.success();
    }

    @GetMapping("/downloadTheory")
    public void downloadTheory(HttpServletResponse response) {
        try {
            //if (!checkToken(token)) {
            //    response.setContentType("application/json");
            //    response.setCharacterEncoding("UTF-8");
            //
            //    ObjectMapper mapper = new ObjectMapper();
            //    mapper.writeValue(response.getWriter(), R.error());
            //    return;
            //}

            XSSFWorkbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Data");
            List<theory> theoryList = theoryService.getBaseMapper().selectList(new QueryWrapper<theory>());
            for (int i = 0; i < theoryList.size(); i++) {
                Row row = sheet.createRow(i);
                row.createCell(0).setCellValue(theoryList.get(i).getTheory());
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=theory_info_" + new Date().getTime() + ".xlsx");
            // 将 Excel 文件写入响应体
            try (OutputStream out = response.getOutputStream()) {
                workbook.write(out);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/setNews")
    public R setNews(@RequestParam("news") String news, @RequestParam("showtime") Integer showtime) {
        newsMapper.truncateNew();
        long beginTimestamp = System.currentTimeMillis();
        long endTimeStamp = beginTimestamp + (1000L * 60 * 60 * showtime);
        Date begintime = new Date(beginTimestamp);
        Date endtime = new Date(endTimeStamp);
        System.out.println(begintime + "," + endtime);
        news n = new news();
        n.setNews(news);
        n.setBegintime(begintime);
        n.setEndtime(endtime);
        int insert = inewsService.getBaseMapper().insert(n);
        return R.success(insert);
    }

    @GetMapping("/newsList")
    public R newsList() {
        List<news> news = inewsService.getBaseMapper().selectList(new QueryWrapper<news>());
        return R.success(news);
    }

    @PostMapping("/stopNews")
    public R stopNews(@RequestParam("id") Integer id) {
        int delete = inewsService.getBaseMapper().deleteById(id);
        if (delete > 0) {
            return R.success();
        }
        return R.error();
    }

    @PostMapping("/uploadImg")
    public R uploadImg(@RequestParam("file") MultipartFile file) throws Exception {
        if (file == null) return R.error("请选择需要上传文件!");
        // 获取上传文件名
        String fileName = file.getOriginalFilename();
        // 定义新的文件名
        String fileNewName = UUID.randomUUID().toString();
        // 获取文件后缀名
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        // 获取文件相对路径
        String revealFilePath = "/" + fileNewName + fileSuffix;
        // 存入数据库
        String filePath = uploadProperties.getUploadDir() + revealFilePath;
        // 判断文件是否存在
        File theoryFile = new File(filePath);
        if (theoryFile.exists()) {
            theoryFile.delete();
        }
        file.transferTo(theoryFile);
        return R.success(revealFilePath);
    }

    @PostMapping(value = "/addHomeAds")
    public R addHomeAds(@RequestBody HomeAds homeAds) {
        Date releaseTime = new Date();
        homeAds.setReleaseTime(releaseTime);
        homeAdsMapper.truncateHomeAdsTable();
        int insert = homeAdsService.getBaseMapper().insert(homeAds);
        if (insert > 0) {
            return R.success();
        }
        return R.error();
    }

    @PostMapping(value = "/stopHomeAds")
    public R stopHomeAds() {
        homeAdsMapper.truncateHomeAdsTable();
        return R.success();
    }

    @GetMapping(value = "/homeAdsList")
    public R homeAdsList() {
        List<HomeAds> homeAds = homeAdsService.getBaseMapper().selectList(new QueryWrapper<HomeAds>());
        return R.success(homeAds);
    }

    @PostMapping(value = "/addFloorAds")
    public R addFloorAds(@RequestBody FloorAds floorAds) {
        Date releaseTime = new Date();
        floorAds.setReleaseTime(releaseTime);
        int insert = floorAdsService.getBaseMapper().insert(floorAds);
        if (insert > 0) {
            return R.success();
        }
        return R.error();
    }

    @PostMapping(value = "/stopFloorAds")
    public R stopFloorAds(@RequestBody FloorAds floorAds) {
        int i = floorAdsService.getBaseMapper().deleteById(floorAds);
        if (i > 0) {
            return R.success();
        }
        return R.error();
    }

    @GetMapping(value = "/getFloorAdsList")
    public R getFloorAdsList() {
        List<FloorAds> release_time = floorAdsService.getBaseMapper().selectList(new QueryWrapper<FloorAds>().orderByDesc("release_time"));
        return R.success(release_time);
    }

    @GetMapping(value = "/getRandomTheory")
    public R getRandomTheory() {
        List<news> newsList = inewsService.getBaseMapper().selectList(new QueryWrapper<news>());
        List<theory> theoryList = theoryService.getBaseMapper().selectList(new QueryWrapper<theory>());
        theory id = new theory();
        if (theoryList.size() > 0) {
            int min = 1;
            int max = theoryList.size();
            Random rand = new Random();
            int randonNumber = rand.nextInt(max - min + 1) + min;
            id = theoryService.getBaseMapper().selectOne(new QueryWrapper<theory>().eq("id", randonNumber));
        }
        String news = newsList.size() == 0 ? id.getTheory() : newsList.get(0).getNews();
        return R.success(news);
    }
}
